import org.junit.jupiter.api.Test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class StudentDBGUI extends JFrame {
    // 数据库连接信息（根据实际情况修改）
    private static final String DB_URL = "jdbc:mysql://localhost:3306/studentdb?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    // 界面组件
    private JTextField tfId, tfName, tfGender, tfClass, tfTel, tfBirthday;
    private JTextField tfQueryClass;      // 用于输入班级查询
    private JTextArea textArea;           // 用于显示查询结果

    public StudentDBGUI() {
        setTitle("学生信息管理");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 上部面板：输入字段
        JPanel inputPanel = new JPanel(new GridLayout(3, 4, 5, 5));
        inputPanel.setBorder(BorderFactory.createTitledBorder("学生信息输入"));

        inputPanel.add(new JLabel("学号(id):"));
        tfId = new JTextField();
        inputPanel.add(tfId);

        inputPanel.add(new JLabel("姓名(name):"));
        tfName = new JTextField();
        inputPanel.add(tfName);

        inputPanel.add(new JLabel("性别(gender):"));
        tfGender = new JTextField();
        inputPanel.add(tfGender);

        inputPanel.add(new JLabel("班级(class):"));
        tfClass = new JTextField();
        inputPanel.add(tfClass);

        inputPanel.add(new JLabel("电话(tel):"));
        tfTel = new JTextField();
        inputPanel.add(tfTel);

        inputPanel.add(new JLabel("生日(birthday):"));
        tfBirthday = new JTextField();
        inputPanel.add(tfBirthday);

        // 中部面板：按钮
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton btnInsert = new JButton("插入");
        JButton btnUpdate = new JButton("修改");
        JButton btnDelete = new JButton("删除");
        buttonPanel.add(btnInsert);
        buttonPanel.add(btnUpdate);
        buttonPanel.add(btnDelete);

        // 下部面板：查询
        JPanel queryPanel = new JPanel(new FlowLayout());
        queryPanel.setBorder(BorderFactory.createTitledBorder("根据班级查询"));
        queryPanel.add(new JLabel("班级:"));
        tfQueryClass = new JTextField(10);
        queryPanel.add(tfQueryClass);
        JButton btnQuery = new JButton("查询");
        queryPanel.add(btnQuery);

        // 结果显示区域
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        // 布局
        add(inputPanel, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
        add(queryPanel, BorderLayout.SOUTH);
        add(scrollPane, BorderLayout.EAST);
        scrollPane.setPreferredSize(new Dimension(300, 0));

        // 按钮事件
        btnInsert.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                insertStudent();
            }
        });

        btnUpdate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateStudent();
            }
        });

        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteStudent();
            }
        });

        btnQuery.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryByClass();
            }
        });
    }

    /**
     * 获取数据库连接
     */
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // 或 com.mysql.jdbc.Driver
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    /**
     * 插入学生信息
     */
    private void insertStudent() {
        String sql = "INSERT INTO student (id, name, gender, class, tel, birthday) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, tfId.getText().trim());
            ps.setString(2, tfName.getText().trim());
            ps.setString(3, tfGender.getText().trim());
            ps.setString(4, tfClass.getText().trim());
            ps.setString(5, tfTel.getText().trim());
            ps.setString(6, tfBirthday.getText().trim());
            int result = ps.executeUpdate();
            if (result > 0) {
                JOptionPane.showMessageDialog(this, "插入成功！");
            } else {
                JOptionPane.showMessageDialog(this, "插入失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }

    /**
     * 修改学生信息（根据学号）
     */
    private void updateStudent() {
        String sql = "UPDATE student SET name = ?, gender = ?, class = ?, tel = ?, birthday = ? WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, tfName.getText().trim());
            ps.setString(2, tfGender.getText().trim());
            ps.setString(3, tfClass.getText().trim());
            ps.setString(4, tfTel.getText().trim());
            ps.setString(5, tfBirthday.getText().trim());
            ps.setString(6, tfId.getText().trim());
            int result = ps.executeUpdate();
            if (result > 0) {
                JOptionPane.showMessageDialog(this, "修改成功！");
            } else {
                JOptionPane.showMessageDialog(this, "修改失败或找不到对应学号！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }

    /**
     * 删除学生信息（根据学号）
     */
    private void deleteStudent() {
        String sql = "DELETE FROM student WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, tfId.getText().trim());
            int result = ps.executeUpdate();
            if (result > 0) {
                JOptionPane.showMessageDialog(this, "删除成功！");
            } else {
                JOptionPane.showMessageDialog(this, "删除失败或找不到对应学号！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }

    /**
     * 根据班级查询学生信息
     */
    private void queryByClass() {
        String sql = "SELECT * FROM student WHERE class = ?";
        textArea.setText(""); // 清空显示区域
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, tfQueryClass.getText().trim());
            ResultSet rs = ps.executeQuery();
            // 将查询结果显示到 textArea
            while (rs.next()) {
                String line = String.format("学号:%s, 姓名:%s, 性别:%s, 班级:%s, 电话:%s, 生日:%s",
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("gender"),
                        rs.getString("class"),
                        rs.getString("tel"),
                        rs.getDate("birthday").toString());
                textArea.append(line + "\n");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 可选：设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // 忽略
        }

        SwingUtilities.invokeLater(() -> {
            StudentDBGUI frame = new StudentDBGUI();
            frame.setVisible(true);
        });
    }
}
